package com.heima.web.action;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;

import com.heima.tools.PageBean;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

public class BaseAction<T> extends ActionSupport implements ModelDriven<T> {
	protected T model;
	protected PageBean pageBean = new PageBean();
	protected DetachedCriteria criteria=null;
	private int rows;
	private int page;
	
	public void setRows(int rows) {
		pageBean.setPageSize(rows);
		this.rows = rows;
	}
	public void setPage(int page) {
		pageBean.setCurrentPage(page);
		this.page = page;
	}
	@Override
	public T getModel() {
		return model;
	}
	public BaseAction(){
		try {
			Type type = ((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
			Class clazz = (Class)type;
			model=(T) clazz.newInstance();
			criteria = DetachedCriteria.forClass(clazz);
			pageBean.setCriteria(criteria);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void pageBeanQuery(String...args){
		try {
			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.setExcludes(args);
			JSONObject json = JSONObject.fromObject(pageBean, jsonConfig);
			String string = json.toString();
			ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
			ServletActionContext.getResponse().getWriter().print(string);
		} catch (IOException e) {
			
			e.printStackTrace();
		}
	}
}
